package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.CheckItemDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

//解决老版本开启事务对外暴露接口不相符
@Service(interfaceClass = CheckItemService.class)
public class CheckItemServiceImpl implements CheckItemService {

    @Autowired
    private CheckItemDao checkItemDao;


    @Override
    public CheckItem findById(Integer id){
        if(id != null){
            return checkItemDao.findById(id);
        }
        return null;
    }
    /**
     * 查询检查项
     *
     * @param queryPageBean 对查询条件进行封装
     * @return
     */
    @Override
    public PageResult findList(QueryPageBean queryPageBean) {

//        if (!StringUtils.isEmpty(queryPageBean.getQueryString())) {
//            queryPageBean.setQueryString("%" + queryPageBean.getQueryString() + "%");
//        }
        //分页参数
        //thread local上记录分页信息
        Page<CheckItem> pageInfo = PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize())
                .doSelectPage(() -> {
            checkItemDao.findList(queryPageBean.getQueryString());
        });

        //添加代码，抛出异常

        //查询时，取出来这个threadlocal中的信息，帮你自动做分页

        //PageInfo<CheckItem> pageInfo = new PageInfo<>(checkItemList);
        PageResult pageResult = new PageResult(pageInfo.getTotal(),pageInfo.getResult());
        return pageResult;
    }

    @Override
    @Transactional
    public Integer insert(CheckItem checkItem){
        Integer insert = checkItemDao.insert(checkItem);
        //checkItem.getId();
        return insert;
    }

    @Override
    @Transactional
    public Integer delete(Integer id) {
        //判断是否被关联表 关联
        if(checkItemDao.selectRelationById(id) > 0){
            return -1;
        }
         //执行删除
        return checkItemDao.delete(id);
    }

    @Override
    @Transactional
    public Integer update(CheckItem checkItem) {
        if(checkItem != null){
            return checkItemDao.update(checkItem);
        }
        return null;
    }

    @Override
    public List<CheckItem> findAll() {
        List<CheckItem> all = checkItemDao.findAll();
        if (all.isEmpty()){
            return null;
        }
        return all;
    }
}
